package com.zggk.lzz.dtfdbridge;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MultiPointItem;
import com.amap.api.maps.model.MultiPointOverlay;
import com.amap.api.maps.model.MultiPointOverlayOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.zggk.lzz.R;
import com.zggk.lzz.bridgetmx.BridgeMxBean;
import com.zggk.lzz.dtfbevent.DtfbEventActivity;
import com.zggk.lzz.dtfbtunnel.DtfbTunnelActivity;
import com.zggk.lzz.mvp.MVPBaseActivity;
import com.zggk.lzz.util.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class DtfdBridgeActivity extends MVPBaseActivity<DtfdBridgeContract.View, DtfdBridgePresenter> implements DtfdBridgeContract.View {


    @Bind(R.id.map)
    MapView mMapView;
    @Bind(R.id.back_lay)
    RelativeLayout backLay;
    @Bind(R.id.lx_te)
    ImageView lxTe;
    @Bind(R.id.ql_te)
    ImageView qlTe;
    @Bind(R.id.sd_te)
    ImageView sdTe;
    @Bind(R.id.bridge_name)
    TextView bridgeName;
    @Bind(R.id.delete)
    TextView delete;
    @Bind(R.id.halving_line)
    View halvingLine;
    @Bind(R.id.bridge_img)
    ImageView bridgeImg;
    @Bind(R.id.tjfw_te)
    TextView tjfwTe;
    @Bind(R.id.qlzs_te)
    TextView qlzsTe;
    @Bind(R.id.zlcs_te)
    TextView zlcsTe;
    @Bind(R.id.re_lay)
    RelativeLayout reLay;
    @Bind(R.id.bridge2_img)
    ImageView bridge2Img;
    @Bind(R.id.qlwz_te)
    TextView qlwzTe;
    @Bind(R.id.kjfl_te)
    TextView kjflTe;
    @Bind(R.id.qlqc_te)
    TextView qlqcTe;
    @Bind(R.id.szzq_te)
    TextView szzqTe;
    @Bind(R.id.re2_lay)
    RelativeLayout re2Lay;
    @Bind(R.id.obvious_lay)
    RelativeLayout obviousLay;
    @Bind(R.id.disease_new_parent_layout)
    RelativeLayout diseaseNewParentLayout;
    @Bind(R.id.dw_img)
    ImageButton dwImg;
    @Bind(R.id.sj_te)
    ImageView sjTe;
    private AMap aMap;

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_dtfb_bridge;
    }

    public static DtfdBridgeActivity test_a = null;
    private MyLocationStyle myLocationStyle;
    private double Lat1;
    private double Lon1;
    private double Lat2;
    private double Lon2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        test_a = this;
        initView(savedInstanceState);
        initSearch();
        initData();
        initLan();
    }

    private void initView(Bundle savedInstanceState) {
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
    }

    private void initLan() {
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
//        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//只定位一次。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                Lat1 = location.getLatitude();
                Lon1 = location.getLongitude();
            }
        });
    }

    private void initData() {
        mPresenter.getData(DtfdBridgeActivity.this);
    }

    @OnClick({R.id.dw_img, R.id.back_lay, R.id.sd_te, R.id.lx_te, R.id.sj_te, R.id.delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dw_img:
                LatLng latLng = new LatLng(Lat1, Lon1);
                aMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                break;
            case R.id.back_lay:
                finish();
                break;
            case R.id.lx_te:
                finish();
                break;
            case R.id.sd_te:
                startActivity(new Intent(DtfdBridgeActivity.this, DtfbTunnelActivity.class));
                finish();
                break;
            case R.id.sj_te:
                startActivity(new Intent(DtfdBridgeActivity.this, DtfbEventActivity.class));
                finish();
                break;
            case R.id.delete:
                aMap.clear();
                initSearch();
                initData();
                initLan();
                break;

        }
    }


    @Override
    public void getDatas(DtfbBean dtfbBean) {
        reLay.setVisibility(View.VISIBLE);
        re2Lay.setVisibility(View.GONE);
        bridgeName.setText("全省");
        delete.setVisibility(View.GONE);
        tjfwTe.setText("统计范围:  全省");
        qlzsTe.setText("桥梁总数：" + dtfbBean.getBridgeCount() + "座");
        zlcsTe.setText("总里程数：" + dtfbBean.getBridgeSum() + "m");
        //创建MultiPointItem存放，海量点中某单个点的位置及其他信息
        if (dtfbBean.getMinBridge() != null && dtfbBean.getMinBridge().size() > 0) {
            Bitmap bitmap4 = BitmapFactory.decodeResource(getResources(), R.drawable.bridge_q_img);
            List<MultiPointItem> list4 = new ArrayList<MultiPointItem>();
            for (int i = 0; i < dtfbBean.getMinBridge().size(); i++) {
                LatLng latLng = new LatLng(dtfbBean.getMinBridge().get(i).getBridgeWD(), dtfbBean.getMinBridge().get(i).getBridgeJD());
                MultiPointItem multiPointItem = new MultiPointItem(latLng);
                multiPointItem.setCustomerId(dtfbBean.getMinBridge().get(i).getBridgeId());
                list4.add(multiPointItem);
            }
            setIc(bitmap4, list4);
        }

        if (dtfbBean.getMidBridge() != null && dtfbBean.getMidBridge().size() > 0) {
            Bitmap bitmap3 = BitmapFactory.decodeResource(getResources(), R.drawable.bridge_x_img);
            List<MultiPointItem> list3 = new ArrayList<MultiPointItem>();
            //创建MultiPointItem存放，海量点中某单个点的位置及其他信息
            for (int i = 0; i < dtfbBean.getMidBridge().size(); i++) {
                LatLng latLng = new LatLng(dtfbBean.getMidBridge().get(i).getBridgeWD(), dtfbBean.getMidBridge().get(i).getBridgeJD());
                MultiPointItem multiPointItem = new MultiPointItem(latLng);
                multiPointItem.setCustomerId(dtfbBean.getMidBridge().get(i).getBridgeId());
                list3.add(multiPointItem);
            }
            setIc(bitmap3, list3);
        }

        if (dtfbBean.getBigBridge() != null && dtfbBean.getBigBridge().size() > 0) {
            Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.bridge_z_img);
            List<MultiPointItem> list2 = new ArrayList<MultiPointItem>();
            //创建MultiPointItem存放，海量点中某单个点的位置及其他信息
            for (int i = 0; i < dtfbBean.getBigBridge().size(); i++) {
                LatLng latLng = new LatLng(dtfbBean.getBigBridge().get(i).getBridgeWD(), dtfbBean.getBigBridge().get(i).getBridgeJD());
                MultiPointItem multiPointItem = new MultiPointItem(latLng);
                multiPointItem.setCustomerId(dtfbBean.getBigBridge().get(i).getBridgeId());
                list2.add(multiPointItem);
            }
            setIc(bitmap2, list2);
        }

        if (dtfbBean.getJumboBridge() != null && dtfbBean.getJumboBridge().size() > 0) {
            Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.bridge_td_img);
            List<MultiPointItem> list1 = new ArrayList<MultiPointItem>();
            //创建MultiPointItem存放，海量点中某单个点的位置及其他信息
            for (int i = 0; i < dtfbBean.getJumboBridge().size(); i++) {
                LatLng latLng = new LatLng(dtfbBean.getJumboBridge().get(i).getBridgeWD(), dtfbBean.getJumboBridge().get(i).getBridgeJD());
                MultiPointItem multiPointItem = new MultiPointItem(latLng);
                multiPointItem.setCustomerId(dtfbBean.getJumboBridge().get(i).getBridgeId());
                list1.add(multiPointItem);
            }
            setIc(bitmap1, list1);
        }

        // 定义海量点点击事件
        AMap.OnMultiPointClickListener multiPointClickListener = new AMap.OnMultiPointClickListener() {
            // 海量点中某一点被点击时回调的接口
            // 返回 true 则表示接口已响应事件，否则返回false
            @Override
            public boolean onPointClick(MultiPointItem pointItem) {
                aMap.clear();
                Lon2 = pointItem.getLatLng().longitude;
                Lat2 = pointItem.getLatLng().latitude;
                mPresenter.getData2(pointItem.getCustomerId(), DtfdBridgeActivity.this);
                return false;
            }
        };
        // 绑定海量点点击事件
        aMap.setOnMultiPointClickListener(multiPointClickListener);
    }

    @Override
    public void getDatas2(BridgeMxBean bridgeMxBean) {
        reLay.setVisibility(View.GONE);
        re2Lay.setVisibility(View.VISIBLE);
        delete.setVisibility(View.VISIBLE);
        bridgeName.setText(bridgeMxBean.getBridgeName());
        qlwzTe.setText("桥梁位置：" + bridgeMxBean.getBridgeCode() + "，" + Utils.getZHMCByZH(bridgeMxBean.getCenterStake()));
        if (bridgeMxBean.getSpanCategoryCode().equals("4")) {
            kjflTe.setText("跨径分类：小桥");
        } else if (bridgeMxBean.getSpanCategoryCode().equals("3")) {
            kjflTe.setText("跨径分类：中桥");
        } else if (bridgeMxBean.getSpanCategoryCode().equals("2")) {
            kjflTe.setText("跨径分类：大桥");
        } else if (bridgeMxBean.getSpanCategoryCode().equals("1")) {
            kjflTe.setText("跨径分类：特大桥");
        }
        qlqcTe.setText("桥梁全长：" + bridgeMxBean.getBridgeTotalLength() + "m");
        szzqTe.setText("所在政区：" + bridgeMxBean.getRegulatoryUnit());
        Double lat = Lat2;
        Double log = Lon2;
        LatLng latLng = new LatLng(lat, log);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));//13为缩放级别

        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.draggable(true);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.bridge_ic_img)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        aMap.addMarker(markerOption);
    }

    private void setIc(Bitmap bitmap, List<MultiPointItem> list) {
        MultiPointOverlayOptions overlayOptions = new MultiPointOverlayOptions();
        overlayOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap));//设置图标
        overlayOptions.anchor(0.5f, 0.5f); //设置锚点
        MultiPointOverlay multiPointOverlay1 = aMap.addMultiPointOverlay(overlayOptions);
        multiPointOverlay1.setItems(list);//将规范化的点集交给海量点管理对象设置，待加载完毕即可看到海量点信息
    }

    /**
     * @Description: (高亮省份)
     * @author 张成昆
     * @date 2020-4-28
     */
    private void initSearch() {
        DistrictSearch search = new DistrictSearch(DtfdBridgeActivity.this);
        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords("广东省");//传入关键字
        query.setShowBoundary(true);//是否返回边界值
        search.setQuery(query);
        search.setOnDistrictSearchListener(new DistrictSearch.OnDistrictSearchListener() {
            @Override
            public void onDistrictSearched(DistrictResult districtResult) {
                if (districtResult == null || districtResult.getDistrict() == null) {
                    return;
                }
                final DistrictItem item = districtResult.getDistrict().get(0);
                if (item == null) {
                    return;
                }
                LatLonPoint centerLatLng = item.getCenter();//得到行政中心点坐标
                if (centerLatLng != null) {  //地图加载时就显示行政区域
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLatLng.getLatitude(), centerLatLng.getLongitude()), 8));//13为缩放级别
                }
                new Thread() {
                    private PolylineOptions polylineOption;

                    public void run() {
                        String[] polyStr = item.districtBoundary();
                        if (polyStr == null || polyStr.length == 0) {
                            return;
                        }
                        for (String str : polyStr) {
                            String[] lat = str.split(";");
                            polylineOption = new PolylineOptions();
                            boolean isFirst = true;
                            LatLng firstLatLng = null;
                            for (String latstr : lat) {
                                String[] lats = latstr.split(",");
                                if (isFirst) {
                                    isFirst = false;
                                    firstLatLng = new LatLng(Double
                                            .parseDouble(lats[1]), Double
                                            .parseDouble(lats[0]));
                                }
                                polylineOption.add(new LatLng(Double
                                        .parseDouble(lats[1]), Double
                                        .parseDouble(lats[0])));
                            }
                            if (firstLatLng != null) {
                                polylineOption.add(firstLatLng);
                            }

                            polylineOption.width(7).color(getResources().getColor(R.color.bule_color));
                            Message message = handler.obtainMessage();
                            message.obj = polylineOption;
                            handler.sendMessage(message);
                        }
                    }
                }.start();
            }
        });//绑定监听器
        search.searchDistrictAnsy();//开始搜索
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            PolylineOptions polylineOption = (PolylineOptions) msg.obj;
            aMap.addPolyline(polylineOption);
        }
    };

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

}
